package com.hmdp.DistributedLock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisLockImpl implements ILock {

    private StringRedisTemplate stringRedisTemplate;
    private static final String LOCK_PREFIX = "lock:";
    private String lockKeyName; // 锁的名称
    private ThreadLocal<String> lockValue = new ThreadLocal<>();

    public RedisLockImpl(StringRedisTemplate stringRedisTemplate, String lockKeyName) {
        if (lockKeyName == null || lockKeyName.isEmpty()) {
            throw new IllegalArgumentException("lockKeyName 不能为空");
        }
        this.stringRedisTemplate = stringRedisTemplate;
        this.lockKeyName = lockKeyName;
    }

    @Override
    public boolean tryLock(long timeoutSeconds) {
        String key = LOCK_PREFIX + lockKeyName;
        String value = UUID.randomUUID().toString() + "_" + Thread.currentThread().getId();
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        boolean isSuccess = Boolean.TRUE.equals(ops.setIfAbsent(key, value, timeoutSeconds, TimeUnit.SECONDS));
        if (isSuccess) {
            lockValue.set(value);
        }
        return isSuccess;
    }

    @Override
    public void unlock() {
        String key = LOCK_PREFIX + lockKeyName;
        String expectedValue = lockValue.get();
        if (expectedValue == null) {
            log.warn("尝试解锁，但未找到锁值：{}", key);
            return;
        }
        String currentValue = stringRedisTemplate.opsForValue().get(key);
        if (expectedValue.equals(currentValue)) {
            stringRedisTemplate.delete(key);
            lockValue.remove();
            log.debug("成功释放锁，键为：{}", key);
        } else {
            log.warn("无法释放锁，键为：{}。预期值：{} 当前值：{}", key, expectedValue, currentValue);
        }
    }
}
